import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Spin, DatePicker, Button, Form } from 'antd';
import { connect } from 'umi';
import moment from 'moment';

import If from '@/components/If';
import OrganizationSelect from '@/components/OrganizationSelect';

import { ColumnProcessor, CommonColumnInterceptor } from '@/pages/SalaryManage/SalaryCalculate/Recheck/ColumnProcessor';
import {
    summaryFieldChooser,
    numberFilter,
    orFilter
} from '@/pages/SalaryManage/SalaryCalculate/Recheck/SummaryProcessor';
import CheckBody from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckBody';
import Search from '@/pages/SalaryManage/components/SuperSearch';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import ExcelExportModal from '@/pages/SalaryManage/SalaryCalculate/SalaryPayoff/components/ExcelExportModal';
import { BUTTON } from '@/pages/SalaryManage/SalaryCalculate/constant/recheckButtonConstant';

import { possessColumn } from '@/pages/SalaryManage/SalaryCalculate/constant/salaryDetailContext';

import { wrapSalaryPayoff } from '@/pages/SalaryManage/utils/pageWrapUtil';

import { fetchOrganizationListAndDefault } from '@/pages/SalaryManage/utils';
import modelType from '@/pages/SalaryManage/SalaryCalculate/constant/modelTypeConstant';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import styles from './index.less';

const { MonthPicker } = DatePicker;

const namespace = 'detailRecheckModel';
const shareNamespace = 'payoffSharedModel';
const DISPATCH_TYPE = {
    initType: `${namespace}/${modelType.E_INIT}`,
    [modelType.E_RESET]: `${namespace}/${modelType.E_RESET}`,
    searchCondition: `${namespace}/${modelType.E_SEARCH_CONDITION}`,
    searchType: `${namespace}/${modelType.E_SEARCH}`,
    tablePageChangeType: `${namespace}/${modelType.E_TABLE_PAGE_CHANGE}`,
    [modelType.E_PAYOFF]: `${namespace}/${modelType.E_PAYOFF}`,
    [modelType.E_EXCEL_EXPORT]: `${namespace}/${modelType.E_EXCEL_EXPORT}`,
    [modelType.E_EXCEL_EXPORT_MODEL]: `${namespace}/${modelType.E_EXCEL_EXPORT_MODEL}`,
    [modelType.E_SHARED_STATE]: `${shareNamespace}/${modelType.E_SHARED_STATE}`
};

const RecheckSummaryChooser = summaryFieldChooser(
    orFilter(numberFilter, col => ({
        success: col.dataIndex === 'employeeName',
        result: { [col.dataIndex]: '合计' }
    }))
);

const RecheckColumnProcessor = () => new ColumnProcessor(possessColumn, CommonColumnInterceptor, null, []);

const DetailPage = wrapSalaryPayoff(props => {
    const {
        sharePeriod,
        shareOrganizationCode,
        period,
        searchModel,
        checkButtonList,
        rowKey,
        tableHeader,
        currentRecord,
        columnProcessor = RecheckColumnProcessor(),
        modalVisible,
        summaryFields = RecheckSummaryChooser,
        pagination,
        dispatch,
        dispatchType = DISPATCH_TYPE,
        dataSource = [],
        tableLoading,
        tableProps = {}
    } = props;

    const [organizationTreeData, setOrganizationTreeData] = useState({});

    const { departmentCode, organizationCode } = searchModel;

    useEffect(() => {
        const resetInit = async () => {
            dispatch({
                type: dispatchType.reset,
                payload: {
                    organizationCode: shareOrganizationCode
                }
            });

            const {
                organizationResponse: response,
                defaultOrganizationCode: defaultSelectCode
            } = await fetchOrganizationListAndDefault(shareOrganizationCode);
            setOrganizationTreeData(response);
            if (shareOrganizationCode !== defaultSelectCode) {
                dispatch({
                    type: dispatchType.sharedState,
                    payload: {
                        shareOrganizationCode: defaultSelectCode,
                        sharePeriod: undefined
                    }
                });
                dispatch({
                    type: dispatchType.reset,
                    payload: {
                        organizationCode: defaultSelectCode
                    }
                });
            }
        };
        resetInit().then(() => {
            dispatch({ type: dispatchType.initType, payload: sharePeriod });
        });
    }, [
        dispatch,
        dispatchType.initType,
        dispatchType.reset,
        dispatchType.sharedState,
        shareOrganizationCode,
        sharePeriod
    ]);

    const memoDataSource = useMemo(
        () =>
            [].concat(dataSource).map(item => ({
                ...item,
                ...item.dynamicEmployeeInfo,
                ...item.dynamicSalaryPayrollInfo
            })),
        [dataSource]
    );

    const onChange = (date, dateString) => {
        dispatch({
            type: dispatchType.sharedState,
            payload: {
                sharePeriod: dateString
            },
            callback() {
                dispatch({
                    type: dispatchType.initType,
                    payload: dateString
                });
            }
        });
    };

    // 1.设置默认选择月份
    const periodMoment = period ? moment(period) : null;

    const getRightButton = useCallback(code => (checkButtonList || []).find(item => item.code === code), [
        checkButtonList
    ]);

    // 是否需要显示按钮
    const needShowButton = useCallback(
        code => {
            const matchButton = getRightButton(code);

            return matchButton && !matchButton.disabled;
        },
        [getRightButton]
    );

    const HasRight = useCallback(({ code, children }) => (needShowButton(code) ? children : null), [needShowButton]);

    const payoffFn = () => {
        dispatch({
            type: dispatchType[modelType.E_PAYOFF]
        });
    };
    const excelExportFn = () => {
        dispatch({
            type: dispatchType[modelType.E_EXCEL_EXPORT_MODEL],
            payload: true
        });
    };

    const handleOrgChange = val => {
        dispatch({
            type: dispatchType.sharedState,
            payload: {
                shareOrganizationCode: val,
                sharePeriod: undefined
            },
            callback() {
                dispatch({
                    type: dispatchType.searchCondition,
                    payload: {
                        organizationCode: val
                    },
                    callback() {
                        dispatch({
                            type: dispatchType.initType
                        });
                    }
                });
            }
        });
    };

    const handleDepChange = val => {
        dispatch({
            type: dispatchType.searchCondition,
            payload: {
                departmentCode: val
            },
            callback() {
                dispatch({
                    type: dispatchType.searchType
                });
            }
        });
    };

    return (
        <div className={salaryStyle.salaryWrapper}>
            <Spin spinning={tableLoading}>
                <Search.Wrapper style={{ marginTop: 20 }}>
                    <TwoColHead
                        style={{ margin: 0, width: '100%' }}
                        left={
                            <>
                                <Search.Item label="机构">
                                    <OrganizationSelect
                                        isStrictly
                                        allowClear={false}
                                        isNeedPermission
                                        style={{ width: 220 }}
                                        value={organizationCode}
                                        treeDataFromProp
                                        treeDataList={organizationTreeData}
                                        onChange={handleOrgChange}
                                        unLoading
                                    />
                                </Search.Item>
                                <Search.Item>
                                    <OrganizationSelect
                                        isStrictly
                                        isFunctional
                                        style={{ width: 150 }}
                                        value={departmentCode}
                                        onChange={handleDepChange}
                                        extraQuery={{ auditStatus: 2 }}
                                        unLoading
                                    />
                                </Search.Item>
                                <Search.Item label="月份">
                                    <MonthPicker
                                        onChange={onChange}
                                        value={periodMoment}
                                        style={{ width: '110px' }}
                                        allowClear={false}
                                    />
                                </Search.Item>
                                <HasRight code={BUTTON.PO_PAYOFF}>
                                    <Button type="primary" onClick={payoffFn}>
                                        执行付款
                                    </Button>
                                </HasRight>
                                <HasRight code={BUTTON.PO_PAYOFF_EXCEL_EXPORT}>
                                    <Button type="primary" onClick={excelExportFn}>
                                        导出
                                    </Button>
                                </HasRight>
                            </>
                        }
                    />
                </Search.Wrapper>
                <If condition={currentRecord?.fileName}>
                    <Form layout="inline" className={styles.tableInfo}>
                        <Form.Item label="上次操作设置"></Form.Item>
                        <Form.Item label="操作人">
                            {' '}
                            <EmptyPlaceHolder value={currentRecord.operator} />
                        </Form.Item>
                        <Form.Item label="Excel表名">
                            <EmptyPlaceHolder value={currentRecord.fileName} />
                        </Form.Item>
                        <Form.Item label="摘要">
                            <EmptyPlaceHolder value={currentRecord.description} />
                        </Form.Item>
                        <Form.Item label="备注">
                            <EmptyPlaceHolder value={currentRecord.remark} />
                        </Form.Item>
                    </Form>
                </If>
                <CheckBody
                    rowKey={rowKey}
                    tableHeader={tableHeader}
                    columnProcessor={columnProcessor}
                    summaryFields={summaryFields}
                    dataSource={memoDataSource}
                    pagination={pagination}
                    dispatch={dispatch}
                    searchModel={searchModel}
                    dispatchType={dispatchType}
                    // tableLoading={tableLoading}
                    tableProps={tableProps}
                    hideSelection
                />
                <ExcelExportModal
                    dispatchType={dispatchType}
                    dispatch={dispatch}
                    modalVisible={modalVisible}
                    period={period}
                />
            </Spin>
        </div>
    );
});
export default connect(({ detailRecheckModel, payoffSharedModel }) => ({
    ...detailRecheckModel,
    ...payoffSharedModel
}))(DetailPage);
